<?php

declare(strict_types=1);

namespace app\common\service;

use app\common\model\auth\AdminModel;
use app\common\model\auth\AdminRoleModel;
use app\common\model\auth\RolePermissionModel;
use Dengje\Pxy\BaseService;
use think\facade\Db;

class RoleService extends BaseService
{
    protected $model = null;


    public function __construct()
    {

        $this->model =  new \app\common\model\auth\RoleModel();
    }

    public function list()
    {
        $where[] = ['id', '>', 1];
        $name = request()->get('name');
        if ($name) $where[] = ['name', '=', $name];
        $remark = request()->get('remark');
        if ($remark) $where[] = ['remark', '=', $remark];
        if (request()->get('page_size/d')) {
            $list = $this->model->where($where)->order(['sort' => 'asc'])->paginate(request()->get('page_size/d', 10));
        } else {
            $list = $this->model->where($where)->order(['sort' => 'asc'])->select();
        }
        $list->map(function ($v) {
            $v['number'] = AdminRoleModel::where('role_id', $v['id'])->count();
            return $v;
        });
        return $list;
    }

    public function create($data)
    {
        $codes = $data['codes'];
        unset($data['codes']);
        $role =  $this->model->create($data);
        RolePermissionModel::updateRel($role->id, $codes);
        unset($data['codes']);
        return $role;
    }

    public function update($id, $data)
    {
        $data = $this->preExcludeFields($data);
        $codes = $data['codes'];
        unset($data['codes']);
        RolePermissionModel::updateRel($id, $codes);
       
        return $this->model->where('id', $id)->update($data);
    }

    public function detail($id)
    {
        $detail = $this->model->where('id', $id)->find();
        $detail['codes'] = RolePermissionModel::where('role_id', $id)->column('code');
        return $detail;
    }

    public function delete($id)
    {
      
        Db::startTrans();
        try{
            
            $admin = AdminRoleModel::where('role_id', $id)->find();
            if ($admin) {
                throw new \Exception('该角色有管理员使用，不能删除');
            }
            RolePermissionModel::where('role_id', $id)->delete();
            $role =  $this->model->where('id', $id)->delete();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
        
        return  $role;
    }
}
